package com.example.mcdonaldapplication.activity

import android.annotation.SuppressLint
import android.content.Context
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Looper
import android.widget.Toast
import com.example.mcdonaldapplication.databinding.ActivityExchangeByIntegralBinding
import com.example.mcdonaldapplication.info.ServerIP
import okhttp3.FormBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import kotlin.concurrent.thread

//可兑换的商品详情信息
class ExchangeByIntegralActivity : AppCompatActivity() {

    private val serverIp = ServerIP.getIp()
    private lateinit var binding: ActivityExchangeByIntegralBinding

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityExchangeByIntegralBinding.inflate(layoutInflater)
        setContentView(binding.root)
        supportActionBar?.hide()

        val prefs = getSharedPreferences("user", Context.MODE_PRIVATE)
        val integral = prefs.getInt("integral", 0)
        val uid = intent.getIntExtra("uid",0)
        val gid = intent.getIntExtra("gid",0)
        val price = intent.getIntExtra("integral",0)
        val name = intent.getStringExtra("name")
        val content = intent.getStringExtra("content")
//        val sales = intent.getStringExtra("sales")
        binding.sales.text = "100+"
        binding.name.text = name
        binding.price.text = price.toString()
        binding.tvContent.text = content
        binding.exchange.setOnClickListener {
            exchangeGoods(gid,uid,this)
            delIntegral(integral - price)
            finish()
        }
    }

    private fun exchangeGoods(gid: Int,uid: Int,context: Context){
        thread {
            //post方式提交的数据
            val formBody: FormBody = FormBody.Builder()
                .add("uid", uid.toString())
                .add("gid", gid.toString())
                .build()
            val client = OkHttpClient()
            val request = Request.Builder()
                .url("http://${serverIp}/ticket/exchangeGoods")
                .post(formBody)
                .build()
            val response = client.newCall(request).execute()
            val responseData = response.body.string()
            parseJsonExchangeByIntegral(responseData,context)
        }
    }

    private fun delIntegral(integral:Int){
        val editor = getSharedPreferences("user", Context.MODE_PRIVATE).edit()
        editor.putInt("integral", integral)
        editor.apply()
    }

    private fun parseJsonExchangeByIntegral(json: String,context: Context){
        val jsonObject = JSONObject(json)
        Looper.prepare()
        Toast.makeText(context,jsonObject.optString("message"), Toast.LENGTH_SHORT).show()
        Looper.loop()
    }
}